package com.sh.caryr.erp.controller.basis;

import com.sh.caryr.erp.entity.PageResultMessage;
import com.sh.caryr.erp.entity.ResultMessage;
import com.sh.caryr.erp.custmz.UserAuthorityContainer;
import com.sh.caryr.erp.entity.trade.Order;
import com.sh.caryr.erp.entity.user.User;
import com.sh.caryr.erp.excel.ImportFromExcel;
import com.sh.caryr.erp.service.IOrderService;
import com.sh.caryr.erp.util.ERPConstants;
import com.sh.caryr.erp.util.UtilityTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

@RestController
@SessionAttributes("user")
@RequestMapping("/api/upload")
public class UploadlController {

    @Autowired
    private IOrderService orderService;

    @RequestMapping(value = "/trades", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    public ResultMessage<List<Order>> uploadTrades(
            HttpServletRequest request,
            @RequestParam("uploadFile") MultipartFile file,
            @ModelAttribute("user") User operator) throws Exception {
        List<Order> tradesFromClient = new ArrayList<>();
        request.getSession().removeAttribute("uploadTrades");
        try {
            //Upload file to temp file
            String folderPath = request.getServletContext().getRealPath("/") + ERPConstants.TEMP_FOLDER_NAME + "/" + "trade/";
            File folder = new File(folderPath);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            String filePath = folderPath + UUID.randomUUID().toString().substring(0, 9) + file.getOriginalFilename();
            File savedFile = new File(filePath);
            file.transferTo(savedFile);
            //Convert file to trade object
            String authStr = UserAuthorityContainer.convertUserAuthToString(operator);
            boolean hasUpdateAuth = ERPConstants.SYS_SUPER_USERNAME.equals(operator.getName()) ||
                    operator.getIsSuperuser() == ERPConstants.ENITYT_ACTIVE ||
                    authStr.contains("salesOrder_update");
            tradesFromClient = ImportFromExcel.importTrade(savedFile, hasUpdateAuth);
            for (Order order : tradesFromClient) {
                order.setCreateBy(operator.getId());
                order.setCoco(operator.getCoco());
            }
            savedFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //Get trade base client trades and db trades.
        List<Order> orderList = orderService.getOrderByUpdate(tradesFromClient);
        request.getSession().setAttribute("uploadTrades", orderList);
        return new PageResultMessage<>(tradesFromClient, tradesFromClient.size());
    }

    @RequestMapping(value = "/trades", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public ResultMessage<List<Order>> getUploadTrades(
            HttpServletRequest request,
            @ModelAttribute("user") User operator) throws Exception {
        List<Order> list;
        List<Order> uploadOrder = (List<Order>) request.getSession().getAttribute("uploadTrades");
        if (uploadOrder == null) {
            list = new ArrayList<>();

        } else {
            list = uploadOrder;
        }
        return new PageResultMessage<>(list, list.size());
    }

    @RequestMapping(value = "/saveTrades/{ids}", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public ResultMessage<List<Order>> saveUploadTrades(
            HttpServletRequest request,
            @PathVariable String ids,
            @ModelAttribute("user") User operator) throws Exception {

        Set<Integer> indexes = UtilityTool.convertStringArray2Set(ids.split(","));
        List<Order> sessionOrders = (List<Order>) request.getSession().getAttribute("uploadTrades");
        List<Order> updateOrders = new ArrayList<>();
        if (sessionOrders != null && !sessionOrders.isEmpty()) {
            for (int i = 0; i < sessionOrders.size(); i++) {
                if (indexes.contains(i)) {
                    updateOrders.add(sessionOrders.get(i));
                }
            }
            orderService.insertOrdersFromExcel(updateOrders);
            request.getSession().removeAttribute("uploadTrades");
        } else {
            updateOrders = sessionOrders;
        }
        return new PageResultMessage<>(updateOrders, updateOrders.size());
    }
}
